﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Com.Binaria.SISCOB.Web.Model;
using Com.Binaria.SISCOB.Funcional.DTO;
using System.IO;
using OfficeOpenXml;
using System.Configuration;

namespace Com.Binaria.SISCOB.Web.Paginas.Reporte
{
    /// <summary>
    /// Descripción breve de $codebehindclassname$
    /// </summary>
    public class ExportHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
            byte[] bytes = null;
            string[] sValues = new string[] { "Fail", "Egreso", "Ingreso", "Caducados" };
            int idxValue = 0;
            //Analizar solicitud
            string tipo = context.Request["tipo"] ?? "EGR";
            if (string.Compare(tipo, "EGR", StringComparison.OrdinalIgnoreCase) == 0)
            {
                idxValue = 1;
                //Recuperar Data
                EgresoRepository oRep = new EgresoRepository();
                EgresoFuncionalDTO[] dto = oRep.GetAll().ToArray();
                //Preparar documento
                if (dto != null && dto.Length > 0)
                    bytes = CreateDocument(dto);
            }
            else if (string.Compare(tipo, "ING", StringComparison.OrdinalIgnoreCase) == 0)
            {
                idxValue = 2;
                //Recuperar Data
                IngresoRepository oRep = new IngresoRepository();
                IngresoFuncionalDTO[] dto = oRep.GetAll().ToArray();
                //Preparar documento
                if (dto != null && dto.Length > 0)
                    bytes = CreateDocument(dto);
            }
            else if (string.Compare(tipo, "CAD", StringComparison.OrdinalIgnoreCase) == 0)
            {
                idxValue = 3;
                //
                EgresoFuncionalDTO oItem = new EgresoFuncionalDTO()
                {
                    IsCaducados = true,
                    FchConsulta = new DateTime(2005,3,6),
                    DiasMaximos = Convert.ToInt16(ConfigurationManager.AppSettings["DIAS_MAXIMOS"])
                };
                //Recuperar Data
                EgresoRepository oRep = new EgresoRepository();
                EgresoFuncionalDTO[] dto = oRep.GetBy(oItem).ToArray();
                //Preparar documento
                if (dto != null && dto.Length > 0)
                    bytes = CreateDocumentCaducados(dto);
            }

            if (bytes != null)
            {
                //Write it back to the client
                context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                context.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}{1}.xlsx", sValues[idxValue], DateTime.Now.ToString("yyyyMMdd")));
                context.Response.BinaryWrite(bytes);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        byte[] CreateDocument(EgresoFuncionalDTO[] dto)
        {
            byte[] oRes = null;
            FileInfo tlpFile = new FileInfo(HttpContext.Current.Server.MapPath("~/Assets/tlp_egreso.xlsx"));
            //
            using (ExcelPackage pkg = new ExcelPackage(tlpFile, true))
            {
                //Open worksheet 1
                ExcelWorksheet ws = pkg.Workbook.Worksheets[1];
                ws.Cells[1, 5].Value = string.Format("{0} {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString());
                //Detalle Informacion
                int iRowIndex = 6;
                ws.InsertRow(iRowIndex, dto.Length);
                for (int i = 0; i < dto.Length; i++)
                {
                    ws.Cells[iRowIndex + i, 1].Value = dto[i].NmrCuenta;
                    ws.Cells[iRowIndex + i, 2].Value = dto[i].FchDocumento;
                    ws.Cells[iRowIndex + i, 3].Formula = dto[i].NmrDocumento;
                    ws.Cells[iRowIndex + i, 4].Value = dto[i].Glosa;
                    ws.Cells[iRowIndex + i, 5].Formula = dto[i].Monto;
                    ws.Cells[iRowIndex + i, 6].Value = dto[i].EstadoText;
                    ws.Cells[iRowIndex + i, 7].Value = dto[i].UserName;
                }
                ws.DeleteRow(iRowIndex - 1, 1);
                // save our new workbook and we are done!
                oRes = pkg.GetAsByteArray();
            }
            return oRes;
        }

        byte[] CreateDocument(IngresoFuncionalDTO[] dto)
        {
            byte[] oRes = null;
            FileInfo tlpFile = new FileInfo(HttpContext.Current.Server.MapPath("~/Assets/tlp_ingreso.xlsx"));
            //
            using (ExcelPackage pkg = new ExcelPackage(tlpFile, true))
            {
                //Open worksheet 1
                ExcelWorksheet ws = pkg.Workbook.Worksheets[1];
                ws.Cells[1, 5].Value = string.Format("{0} {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString());
                //Detalle Informacion
                int iRowIndex = 6;
                ws.InsertRow(iRowIndex, dto.Length);
                for (int i = 0; i < dto.Length; i++)
                {
                    ws.Cells[iRowIndex + i, 1].Value = dto[i].NmrCuenta;
                    ws.Cells[iRowIndex + i, 2].Value = dto[i].FchDocumento;
                    ws.Cells[iRowIndex + i, 3].Formula = dto[i].NmrDocumento;
                    ws.Cells[iRowIndex + i, 4].Value = dto[i].Glosa;
                    ws.Cells[iRowIndex + i, 5].Formula = dto[i].Monto;
                    ws.Cells[iRowIndex + i, 6].Value = dto[i].EstadoText;
                    ws.Cells[iRowIndex + i, 7].Value = dto[i].UserName;
                }
                ws.DeleteRow(iRowIndex - 1, 1);
                // save our new workbook and we are done!
                oRes = pkg.GetAsByteArray();
            }
            return oRes;
        }

        byte[] CreateDocumentCaducados(EgresoFuncionalDTO[] dto)
        {
            byte[] oRes = null;
            FileInfo tlpFile = new FileInfo(HttpContext.Current.Server.MapPath("~/Assets/tlp_egreso_caducados.xlsx"));
            //
            using (ExcelPackage pkg = new ExcelPackage(tlpFile, true))
            {
                //Open worksheet 1
                ExcelWorksheet ws = pkg.Workbook.Worksheets[1];
                ws.Cells[1, 5].Value = string.Format("{0} {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString());
                //Detalle Informacion
                int iRowIndex = 6;
                ws.InsertRow(iRowIndex, dto.Length);
                for (int i = 0; i < dto.Length; i++)
                {
                    ws.Cells[iRowIndex + i, 1].Value = dto[i].NmrCuenta;
                    ws.Cells[iRowIndex + i, 2].Value = dto[i].FchDocumento;
                    ws.Cells[iRowIndex + i, 3].Formula = dto[i].NmrDocumento;
                    ws.Cells[iRowIndex + i, 4].Value = dto[i].Glosa;
                    ws.Cells[iRowIndex + i, 5].Formula = dto[i].Monto;
                    ws.Cells[iRowIndex + i, 6].Value = dto[i].EstadoText;
                    ws.Cells[iRowIndex + i, 7].Value = dto[i].UserName;
                }
                ws.DeleteRow(iRowIndex - 1, 1);
                // save our new workbook and we are done!
                oRes = pkg.GetAsByteArray();
            }
            return oRes;
        }

    }
}
